package org.codeart.juc.util;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

import static java.lang.Thread.sleep;

/**
 * 倒计时门栓
 */
public class CountDownLatchDemo {

    public static final ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(3);

    public static final CountDownLatch latch = new CountDownLatch(3);

    public static void exec1() {
        System.out.println("Task A begins.");
        try {
            sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Task A ends.");
        latch.countDown();
    }

    public static void exec2() {
        System.out.println("Task B begins.");
        try {
            sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Task B ends.");
        latch.countDown();
    }

    public static void exec3() {
        System.out.println("Task C begins.");
        try {
            sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Task C ends.");
        latch.countDown();
    }

    public static void main(String[] args) throws InterruptedException {
        try {
            System.out.println("Task main begins.");
            sleep(1000);
            System.out.println("Task main awaits.");
            executor.execute(CountDownLatchDemo::exec1);
            executor.execute(CountDownLatchDemo::exec2);
            executor.execute(CountDownLatchDemo::exec3);
            latch.await();
            System.out.println("Process complete, task main continues.");
        } finally {
            executor.shutdown();
        }
    }

}
